package com.ddy.test.creditcardmanage

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import com.ddy.test.creditcardmanage.model.Card
import com.ddy.test.creditcardmanage.model.CardViewModel
import kotlinx.android.synthetic.main.add_card.*


class AddCard : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.add_card)
        title = "AddCard"

        cardStatementDate.minValue=1
        cardStatementDate.maxValue=28
        cardStatementDate.value=5
        cardDueDate.minValue = 1
        cardDueDate.maxValue = 28
        cardDueDate.value = 23

    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        val inflater = menuInflater
        inflater.inflate(R.menu.add_save, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_add_save -> {
                val varCardNo: String = cardNo.text.toString().trim()
                val varCardComment = cardComment.text.toString().trim()
                val varCardPermanentLine = cardPermanentLine.text.toString().trim()
                val varCardTemporaryLine = cardTemporaryLine.text.toString().trim()
                val varCardStatementAmount = cardStatementAmount.text.toString().trim()
                val varCardStatementDate = cardStatementDate.value
                val varCardDueDate = cardDueDate.value

                val card = Card.newCard(
                    varCardNo,
                    if(varCardComment == "") "未备注" else varCardComment,
                    if(varCardPermanentLine == "") 0F else varCardPermanentLine.toFloat(),
                    if(varCardTemporaryLine == "") 0F else varCardTemporaryLine.toFloat(),
                    if(varCardStatementAmount == "") 0F else varCardStatementAmount.toFloat(),
                    varCardStatementDate, varCardDueDate
                )

                val cardViewModel = CardViewModel(this.application)
                cardViewModel.addCard(card)
                Log.w("SAVE_CARD", "save card id ${card.id}")
                finish()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}